package com.cn.mobileproject.db.dao.impl;

import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.cn.mobileproject.bean.Org;
import com.cn.mobileproject.db.Query;
import com.cn.mobileproject.db.RowMapper;
import com.cn.mobileproject.db.SqliteTemplate;
import com.cn.mobileproject.db.UDatabase;
import com.cn.mobileproject.db.dao.OrgDao;
import com.cn.mobileproject.db.table.OrgTable;

public class OrgDaoImpl implements OrgDao{
	
	private SqliteTemplate sqliteTemplate;

	public OrgDaoImpl() {
		sqliteTemplate = new SqliteTemplate();
	}


	@Override
	public void delete() {
		Query query = new Query();
		query.from(OrgTable.TABLE_NAME);
		sqliteTemplate.delete(query);
	}

	@Override
	public void inserts(List<Org> list) {
		
		if(list==null||list.size()==0) return ;
		try{
			SQLiteDatabase db = UDatabase.getDb(true);
			db.beginTransaction();
			for(Org org: list){
				db.replace(OrgTable.TABLE_NAME, null, orgToValues(org));
			}
			db.setTransactionSuccessful();
			db.endTransaction();
		}catch(Exception e){
		}
	}
	
	private ContentValues orgToValues(Org org) {
		ContentValues v = new ContentValues();
		v.put(OrgTable.FIELD_CODE, org.code);
		v.put(OrgTable.FIELD_ID, org.id);
		v.put(OrgTable.FIELD_LEAF, org.leaf);
		v.put(OrgTable.FIELD_NAME, org.name);
		v.put(OrgTable.FIELD_PARENTID, org.parentId);
		v.put(OrgTable.FIELD_TREECODE, org.treeCode);
		return v;
	}

	private static final class OrgMapper implements
			RowMapper<Org> {
		public Org mapRow(Cursor cursor, int rowNum) {
			Org org = new Org();
			if (cursor != null && cursor.getCount() > 0) {
				org.id=cursor.getString(cursor.getColumnIndex(OrgTable.FIELD_ID));
				org.code=cursor.getString(cursor.getColumnIndex(OrgTable.FIELD_CODE));
				org.leaf=cursor.getString(cursor.getColumnIndex(OrgTable.FIELD_LEAF));
				org.name=cursor.getString(cursor.getColumnIndex(OrgTable.FIELD_NAME));
				org.parentId=cursor.getString(cursor.getColumnIndex(OrgTable.FIELD_PARENTID));
				org.treeCode=cursor.getString(cursor.getColumnIndex(OrgTable.FIELD_TREECODE));
			}
			return org;
		}
	}

	@Override
	public Org searchOrg(String orgid) {
		Query query = new Query();
		query.from(OrgTable.TABLE_NAME, null).where(OrgTable.FIELD_ID+ " = ?",orgid);
		Org org = sqliteTemplate.queryForObject(query,new OrgMapper());
		return org;
	}


	@Override
	public List<Org> searchChildOrg(String orgid) {
		Query query = new Query();
		query.from(OrgTable.TABLE_NAME, null).where(OrgTable.FIELD_PARENTID+ " = ?",orgid);
		return  sqliteTemplate.queryForList(query,new OrgMapper());
	}
}
